package com.ys.controller.api.purchase;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.business.TpProductBasisComponent;
import com.ys.entity.purchase.TcgDistribution;
import com.ys.entity.purchase.TcgPurchaseByPlan;
import com.ys.entity.sys.YsCol;
import com.ys.service.purchase.TcgPurchaseByPlanService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.CheckUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.ToolUtil;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 采购计划
 */
@Controller
@RequestMapping("/api/inter/tcgPurchaseByPlan")
public class ApiInterTcgPurchaseByPlanController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcgPurchaseByPlanController.class);

    @Autowired
    private CommonApiService<TcgPurchaseByPlan> commonApiService;

    @Autowired
    private TcgPurchaseByPlanService tcgPurchaseByPlanService;

    @Autowired
    private CheckUtil checkUtil;

    //菜单id
    private Long menuId = MenuId.TCG_PurchaseByPlan;

    private Long menuIdByWithLogistics = MenuId.TCG_PurchaseByPlan_ByWithLogistics;

    //权限字符
    private final String PERMISSIONS_VIEW = "tcgPurchaseByPlan:view";
    private final String PERMISSIONS_ADD = "tcgPurchaseByPlan:add";
    private final String PERMISSIONS_PRODUCTORDER = "tcgPurchaseByPlan:produceOrder";
    private final String PERMISSIONS_CANCEL = "tcgPurchaseByPlan:cancel";


    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcgPurchaseByPlan setSeachSql(TcgPurchaseByPlan cond){

        cond

                .addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
                .addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
                .addField("U.DeptName AS deptName")//部门
                .addField("U.RoleName AS roleName")//岗位

                .addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') AS auditingTime")//审核时间
                //.addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

                .addLeftJoin("TCG_PurchasePlanGoods B ON B.Pbid = A.Bid ")//计划单母件信息表
                .addField("B.SpBm AS spBm")//母件商品编码
                .addField("B.OrderStatus AS _ys_orderStatus")//订单状态
                .addField("B.SpAmount AS spAmount")//采购数量
                .addField("B.Id AS goodsId")//id
                .addField("B.StoreIntegrity AS storeIntegrity")//入库完整性

                .addLeftJoin("TP_ProductBasis C ON C.Code = B.SpBm ")//商品母件信息表
                .addField("C.Name AS spName")//商品名称

                .addLeftJoin("THR_OperateCompanyApply D ON D.Vgsbm = A.Vgsbm ")//运营公司管理表
                .addField("D.Vgsjc AS vgsjc")//采购公司简称
                .addField("D.Vgsmc AS vgsmc")//采购公司名称

                .addLeftJoin("TCG_PurchaseAddress E ON E.Id = A.PurchaseAddressId ")//采购地址维护
                .addField("E.VGjH + ',' + E.VSfH + ',' + E.VDsH + ',' + E.VCqH + ',' + E.VDzH  AS addressDetail")//地址详情

                .addLeftJoin("TCG_PurchaseByPlanSon F ON F.Pid = B.Id ")//计划单子件信息表
                .addField("F.SubCode AS subCode")//子件编码
                .addField("F.SubAmount AS subAmount")//子件数量
                .addField("F.PurchaseAmount AS purchaseAmount")//计划采购数量
                .addField("F.JgSl AS jgSl")//子件加购数量
                .addField("F.Bprice AS bprice")//子件预估单价
                .addField("F.SubTotalPrice AS subTotalPrice")//子件预估总价
                .addField("F.SubTotalAmount AS subTotalAmount")//子件总数
                .addField("F.StoreAmount AS storeAmount")//入库数量

                .addLeftJoin("TP_ProductBasisComponent G ON G.Code = F.SubCode ")//商品子件信息表
                .addField("G.Name AS subName")//子件名称
                .addField("G.Remark AS subRemark")//子件备注
                .addField("G.LinkIn AS linkIn")//采购链接

                .addLeftJoin("(SELECT SUM((H.PurchaseAmount + H.JgSl) * H.Bprice) AS totalPrice,H.Pbid FROM TCG_PurchaseByPlanSon H GROUP BY H.Pbid) I ON I.Pbid = A.Bid")
                .addField("I.TotalPrice AS totalPrice")//采购预估金额


                .addLeftJoin("TCG_PurchaseByOrder J ON J.PurchasePlanGoodsId = B.Id ")
                .addField("J.Bid AS purchaseOrderBid")//采购订单号
                .addField("J.Id AS purchaseOrderId")//采购订单id
                .addField("J.AliLogisticsState AS logisticsStatus")//物流状态
                .addField("J.AliLogisticsCode AS aliLogisticsCode")//物流单号
                .addField("J.AliLogisticsPlace AS aliLogisticsPlace")//物流渠道
                .addField("J.AliLogisticsBillNo AS aliLogisticsBillNo")//物流运单号
                .addField("J.OrderStatus AS orderStatusByOrder")//采购订单状态
                .addField("J.PurchaseOrderAmount AS purchaseOrderAmount")//采购订单金额(含税)
                .addField("J.FreightCharge AS freightCharge")//运费

                .addLeftJoin("TCG_PurchaseByOrderSon K ON K.PurchasePlanSonId = F.Id ")//采购订单 (子表
                .addField("K.Sku AS sku")//SKU属性
                .addField("K.RealitySku AS realitySku")//实际SKU属性
                .addField("K.SkuId AS skuId")//skuId
                .addField("K.SpecId AS specId")//specId
                .addField("K.RealityPrice AS realityPrice")//子件实际单价
                .addField("K.SubRealityPrice AS subRealityPrice")//子件单价（采购销售）
                .addField("K.RealityCost AS realityCost")//子件总价（采购销售）
                .addField("K.SubCostPrice AS subCostPrice")//子件单价（采购成本）
                .addField("K.CostPriceTotal AS costPriceTotal")//子件总价（采购成本）
                .addField("K.SubCode AS subCode")//子商品编码
                .addField("K.SupplierId AS supplierId")//供应商ID
                .addField("K.SupplierName AS supplierName")//供应商名称
                .addField("K.OrderManageStatus AS _ys_orderManageStatus")//订单管理状态


        .setOrderby("A.Bid DESC");//排序


        return  cond;
    }


    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchaseByPlan cond,String conditions
    ){
        try {
//            cond.addLeftJoin("TCG_PurchasePlanGoods B ON B.Pbid = A.Bid ")
//                    .addLeftJoin("TCG_PurchaseByOrder J ON J.PurchasePlanGoodsId = B.Id ");
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            String orderStatus = ConditionUtil.getConditionValue(conditions, "_ys_orderStatus");//订单状态
            if (orderStatus == null || "".equals(orderStatus)){
                cond.where("B.OrderStatus IN (0,2)");//查询页面默认显示（空、已取消状态）
            }else {
                //-1时显示全部状态
                //非-1时显示选择的对应状态
                if(!"-1".equals(orderStatus)){
                    cond.where("B.OrderStatus  = "+orderStatus);
                }
            }
            cond = commonApiService.dataAuth(menuId, cond);

            LayuiTableVoJA setList = commonApiService.searchLay(cond);

            return setList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }



    /**
     * 查询
     */
    @RequiresPermissions(PERMISSIONS_VIEW)
    @RequestMapping("/searchByWithLogistics")
    @ResponseBody
    public LayuiTableVoJA searchByWithLogistics(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcgPurchaseByPlan cond,String conditions
    ){
        try {
           TcgPurchaseByPlan condByCount = cond.copy();
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
                condByCount.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            String orderStatus = ConditionUtil.getConditionValue(conditions, "_ys_orderStatus");//订单状态
            if (orderStatus == null || "".equals(orderStatus)){
                cond.where("B.OrderStatus IN (0,2)");//查询页面默认显示（空、已取消状态）
                condByCount.where("B.OrderStatus IN (0,2)");
            }else {
                //-1时显示全部状态
                //非-1时显示选择的对应状态
                if(!"-1".equals(orderStatus)){
                    cond.where("B.OrderStatus  = "+orderStatus);
                    condByCount.where("B.OrderStatus  = "+orderStatus);
                }
            }
            cond = commonApiService.dataAuth(menuIdByWithLogistics, cond);
            condByCount = commonApiService.dataAuth(menuIdByWithLogistics, condByCount);


            JSONObject JO = new JSONObject();
            //合计
            {

                //计算累计
                condByCount.setMainTable("TCG_PurchaseByPlan")
                        .addLeftJoin("TCG_PurchasePlanGoods B ON B.Pbid = A.Bid ")
                        .addLeftJoin("TCG_PurchaseByOrder J ON J.PurchasePlanGoodsId = B.Id ");
                // 采购订单金额(含税)
                JO.put("purchaseOrderAmount", condByCount.setFields("ISNULL(SUM(J.PurchaseOrderAmount),0)").sumDecimal());
                // 订单运费
                JO.put("freightCharge", condByCount.setFields("ISNULL(SUM(J.FreightCharge),0)").sumDecimal());
                // 母件采购数量 - 按照订单母件求和
                JO.put("spAmount", condByCount.setFields("ISNULL(SUM(B.SpAmount),0)").sumDecimal());


            }

//            cond.setMainTable("TCG_PurchaseByPlan")
//                    .addLeftJoin("TCG_PurchasePlanGoods B ON B.Pbid = A.Bid ")
//                    .addLeftJoin("TCG_PurchaseByOrder J ON J.PurchasePlanGoodsId = B.Id ");
            cond = setSeachSql(cond);

            LayuiTableVoJA searchList = commonApiService.searchLay(cond);
            searchList.setTotalRow(JO);

            return searchList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }




    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcgPurchaseByPlan cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond = commonApiService.dataAuth(menuId, cond);
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_createUserName");//制单人
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(menuId)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TcgPurchaseByPlan> util = new ExportExcelUtils<>(new TcgPurchaseByPlan());
            String toFilePath = util.exportExcel(listData, listField, "采购计划单");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



    /**
     * 新增
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //新增
            return tcgPurchaseByPlanService.add(params,menuId);
        } catch (Exception e) {
            logger.error("新增出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //修改
            return tcgPurchaseByPlanService.update(params,menuId);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 删除
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/toDel")
    @ResponseBody
    public R toDel(Long id){
        try {
            return tcgPurchaseByPlanService.del(id);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


    /**
     * 流转通过
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcgPurchaseByPlanService.flowPass(id,ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            TcgPurchaseByPlan entity = new TcgPurchaseByPlan().setId(id).queryFirst();
            return tcgPurchaseByPlanService.flowRefuse(entity.getBid(), reason,ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 流转驳回
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            TcgPurchaseByPlan entity = new TcgPurchaseByPlan().setId(id).queryFirst();
            return tcgPurchaseByPlanService.flowInit(entity.getBid(), reason,ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




    /**
     * 根据商品母件编码获取对应所有子件信息
     */
    @RequiresPermissions(PERMISSIONS_ADD)
    @RequestMapping("/getSubInfoByCode")
    @ResponseBody
    public JSONObject getSubInfoByCode(HttpServletRequest request, @RequestParam Map<String, Object> params){
        JSONObject res = new JSONObject();
        try {
            if(checkUtil.isNullByObject(params.get("codes"))){
                res.put("code",R.Code.FAILED.value);
                res.put("msg","商品编码为空");
                return res;
            }
            if(checkUtil.isNullByObject(params.get("vgsbm"))){
                res.put("code",R.Code.FAILED.value);
                res.put("msg","运营公司编码为空");
                return res;
            }
            String codes = params.get("codes").toString();
            String vgsbm = params.get("vgsbm").toString();
            String[] codeArr = codes.split(",");
            List<Map<String,Object>> resList = new ArrayList<>();
            for(String code :codeArr){
                List<Map<String,Object>> subList = new TpProductBasisComponent()
                        .addLeftJoin("TP_ProductActive B ON B.Code = A.Pcode")
                        .addField("B.Code AS spBm")
                        .addField("B.Name AS spName")
                        .addLeftJoin("(SELECT SC.Vgsbm,SC.ProductCode,ISNULL(SUM(SC.ProductNum),0) AS stockAmount FROM TCC_StockControl SC GROUP BY SC.Vgsbm,SC.ProductCode) S " +
                                "ON S.ProductCode = B.Code AND S.Vgsbm = '"+vgsbm+"'")
                        .addField("ISNULL(S.stockAmount,0) AS stockAmount")//母件库存数量

                        .addLeftJoin("(SELECT SC2.Vgsbm,SC2.ProductCode,ISNULL(SUM(SC2.ProductNum),0) AS stockAmount FROM TCC_StockControl SC2 GROUP BY SC2.Vgsbm,SC2.ProductCode) S2 " +
                                "ON S2.ProductCode = A.Code AND S2.Vgsbm = '"+vgsbm+"'")
                        .addField("ISNULL(S2.stockAmount,0) AS subStockAmount")//子件库存数量

                        .addLeftJoin("THR_OperateCompanyApply U ON  U.VGsBm = B.VgsBm")
                            .addField("U.Vgsjc AS vgsjc")
                            .addField("U.Vgsbm AS vgsbm")

                        .setPcode(code)
                        .setOrderby("A.Pcode,A.Code")

                        .queryMap();
                if(subList!=null && subList.size()>0){
                    resList.addAll(subList);
                }
            }

            //返回的提示信息（由于：子件未铺货、无单价、无数量）
            String errorMsg = "";

            //查询铺货信息验证 TCG_Distribution
            if(resList.size()>0){
                List<Map<String,Object>> noDistributionSubCodes = new ArrayList<>();//存放未铺货的商品子件编码集合
                for(Map<String,Object> item : resList){
                    //根据子件编码获取铺货信息
                    int hasDistribution = new TcgDistribution().setScode(item.get("code").toString()).count();
                    if(hasDistribution<=0){
                        noDistributionSubCodes.add(item);
                        //添加提示信息
                        if("".equals(errorMsg)){
                            errorMsg = item.get("code").toString();
                        }else {
                            errorMsg += "、"+item.get("code").toString();
                        }
                    }
                }
                if(noDistributionSubCodes!=null && noDistributionSubCodes.size()>0){
                    //将未铺货的子件 对应母件 底下所有子件去除
                    resList = resList.stream().filter(item->{
                        boolean isNoDel = true;
                        for (Map<String,Object> delItem : noDistributionSubCodes){
                            if(item.get("spBm").toString().equals(delItem.get("spBm").toString())){
                                isNoDel = false;
                            }
                        }
                        return isNoDel;
                    }).collect(Collectors.toList());
                    errorMsg += "商品未铺货完整，请联系采购支持完成铺货再调取。</br>";
                }
            }


            //子件单价验证
            if(resList.size()>0){
                List<Map<String,Object>> noBpriceSubCodes = new ArrayList<>();//存放子件单价为0的商品子件编码集合
                for(Map<String,Object> item : resList){

                    if(item.get("bprice")==null || new BigDecimal(item.get("bprice").toString()).compareTo(BigDecimal.ZERO)<=0){
                        noBpriceSubCodes.add(item);
                        //添加提示信息
                        if("".equals(errorMsg)){
                            errorMsg = item.get("code").toString();
                        }else {
                            errorMsg += "、"+item.get("code").toString();
                        }
                    }
                }
                if(noBpriceSubCodes!=null && noBpriceSubCodes.size()>0){
                    //将无单价的子件 对应母件 底下所有子件去除
                    resList = resList.stream().filter(item->{
                        boolean isNoDel = true;
                        for (Map<String,Object> delItem : noBpriceSubCodes){
                            if(item.get("spBm").toString().equals(delItem.get("spBm").toString())){
                                isNoDel = false;
                            }
                        }
                        return isNoDel;
                    }).collect(Collectors.toList());
                    errorMsg += "商品无单价信息，请完善后再调取。</br>";
                }
            }


            //子件数量验证
            if(resList.size()>0){
                List<Map<String,Object>> noAmountSubCodes = new ArrayList<>();//存放子件数量为0的商品子件编码集合
                for(Map<String,Object> item : resList){
                    if(item.get("num")==null || new BigDecimal(item.get("num").toString()).compareTo(BigDecimal.ZERO)<=0){
                        noAmountSubCodes.add(item);
                        //添加提示信息
                        if("".equals(errorMsg)){
                            errorMsg = item.get("code").toString();
                        }else {
                            errorMsg += "、"+item.get("code").toString();
                        }
                    }
                }
                if(noAmountSubCodes!=null && noAmountSubCodes.size()>0){
                    //将无数量的子件 对应母件 底下所有子件去除
                    resList = resList.stream().filter(item->{
                        boolean isNoDel = true;
                        for (Map<String,Object> delItem : noAmountSubCodes){
                            if(item.get("spBm").toString().equals(delItem.get("spBm").toString())){
                                isNoDel = false;
                            }
                        }
                        return isNoDel;
                    }).collect(Collectors.toList());
                    errorMsg += "商品无数量信息，请完善后再调取。</br>";
                }
            }



            res.put("resList",resList);
            res.put("errorMsg",errorMsg);
            res.put("code",R.Code.SUCCESS.value);
            return res;

        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            res.put("code",R.Code.FAILED.value);
            return res;
        }
    }



    /**
     * 生成订单
     */
    @RequiresPermissions(PERMISSIONS_PRODUCTORDER)
    @RequestMapping("/produceOrder")
    @ResponseBody
    public R produceOrder(HttpServletRequest request, String choooseDatas){
        try {
            //生成订单
            //JSONArray detailJA = JSON.parseArray(choooseDatas);
            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(
                    JSON.parseArray(choooseDatas),
                    e->e.get("goodsId").toString()
            );
            logger.info("生成订单传参:"+detailList);
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                Map<String, Object> params = detailList.get(i);
                //生成订单
                R res = tcgPurchaseByPlanService.produceOrder(params);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (params.get("bid")!=null?"单号："+params.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }

            }
            resMsg = "成功生成订单"+doCount+"条数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }



    /**
     * 取消订单
     */
    @RequiresPermissions(PERMISSIONS_CANCEL)
    @RequestMapping("/cancel")
    @ResponseBody
    public R cancel(HttpServletRequest request, String choooseDatas){
        try {
            //取消订单
            //JSONArray detailJA = JSON.parseArray(choooseDatas);
            List<Map<String, Object>> detailList = ToolUtil.groupsByJSONArray(
                    JSON.parseArray(choooseDatas),
                    e->e.get("goodsId").toString()
            );
            int doCount = 0;
            String resMsg = "";
            for (int i = 0; i < detailList.size(); i++) {
                //JSONObject detailJO = detailJA.getJSONObject(i);
                Map<String, Object> params =detailList.get(i);
                //params.put("goodsId",detailJO.get("goodsId"));
                //生成订单
                R res = tcgPurchaseByPlanService.cancel(params);
                if(res.getCode()==0){
                    doCount ++;
                }else{
                    resMsg += (params.get("bid")!=null?"单号："+params.get("bid"):"")+"；"+res.getMsg()+"</br>";
                }

            }
            resMsg = "成功取消"+doCount+"条数据</br>"+resMsg;
            return R.ok(resMsg);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }




}